package com.yimi.appstore.api;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;

import android.content.Context;
import android.util.Log;

import com.yimi.appstore.util.AboutMobileInfoTools;
import com.yimi.appstore.util.AppException;
import com.yimi.appstore.util.JsonUtil;

public class HttpClientUtil {

	private static final String TAG = "HttpClientUtil";
	public static final String UTF_8 = "UTF-8";
	public static final String DESC = "descend";
	public static final String ASC = "ascend";

	private final static int TIMEOUT_CONNECTION = 20000;
	private final static int TIMEOUT_SOCKET = 200000;
	private final static int RETRY_TIME = 3;

	private static String appUserAgent;

	private static HttpClient getHttpClient() {
		HttpClient httpClient = new HttpClient();
		// 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
		httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
		// 设置 默认的超时重试处理策略
		httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		// 设置 连接超时时间
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT_CONNECTION);
		// 设置 读数据超时时间
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_SOCKET);
		// 设置 字符集
		httpClient.getParams().setContentCharset(UTF_8);
		return httpClient;
	}

	private static GetMethod getHttpGet(String url, /* String cookie, */String userAgent) {
		GetMethod httpGet = new GetMethod(url);
		// 设置 请求超时时间
		httpGet.getParams().setSoTimeout(TIMEOUT_SOCKET);
		httpGet.setRequestHeader("Host", Url.HOST);
		httpGet.setRequestHeader("Connection", "Keep-Alive");
		// httpGet.setRequestHeader("Cookie", cookie);
		httpGet.setRequestHeader("User-Agent", userAgent);
		return httpGet;
	}

	private static PostMethod getHttpPost(String url, /* String cookie, */String userAgent) {
		PostMethod httpPost = new PostMethod(url);
		// 设置 请求超时时间
		httpPost.getParams().setSoTimeout(TIMEOUT_SOCKET);
		httpPost.setRequestHeader("Host", Url.HOST);
		httpPost.setRequestHeader("Connection", "Keep-Alive");
		// httpPost.setRequestHeader("Cookie", cookie);
		httpPost.setRequestHeader("Accept", "application/json");
		// httpPost.setRequestHeader("Content-Length", "310");
		httpPost.setRequestHeader("Content-Type", "application/json");
		return httpPost;
	}

	private static String getUserAgent(Context context) {
		if (appUserAgent == null || appUserAgent == "") {
			AboutMobileInfoTools amit = AboutMobileInfoTools.getInstance(context);
			appUserAgent = amit.getDeviceInfoStr();
		}
		return appUserAgent;
	}

	/**
	 * get请求URL
	 * 
	 * @param url
	 * @throws AppException
	 */
	public static InputStream http_get(Context appContext, String url) throws AppException {
		// String cookie = getCookie(appContext);
		String userAgent = getUserAgent(appContext);

		HttpClient httpClient = null;
		GetMethod httpGet = null;

		String responseBody = "";
		int time = 0;
		do {
			try {
				httpClient = getHttpClient();
				httpGet = getHttpGet(url/* , cookie */, userAgent);
				int statusCode = httpClient.executeMethod(httpGet);
				if (statusCode != HttpStatus.SC_OK) {
					throw AppException.http(statusCode);
				}
				responseBody = httpGet.getResponseBodyAsString();
				break;
			} catch (HttpException e) {
				time++;
				if (time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
					}
					continue;
				}
				// 发生致命的异常，可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				time++;
				if (time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
					}
					continue;
				}
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
				// 释放连接
				httpGet.releaseConnection();
				httpClient = null;
			}
		} while (time < RETRY_TIME);

		responseBody = responseBody.replace('', '?');
		if (responseBody.contains("result") && responseBody.contains("errorCode")) {
			try {

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return new ByteArrayInputStream(responseBody.getBytes());
	}

	/**
	 * 公用post方法
	 * 
	 * @param url
	 * @param params
	 * @param files
	 * @throws AppException
	 */
	public static String _post(Context appContext, String url, Map<String, Object> params, Map<String, File> files)
			throws AppException {
		// String cookie = getCookie(appContext);
		String userAgent = getUserAgent(appContext);

		HttpClient httpClient = null;
		PostMethod httpPost = null;
		String jsonPost = null;
		jsonPost = JsonUtil.mapToJson(params);
		// post表单参数处理
		// int length = (params == null ? 0 : params.size()) + (files == null ?
		// 0 : files.size());
		// Part[] parts = new Part[length];
		// int i = 0;
		// if(params != null)
		// for(String name : params.keySet()){
		// parts[i++] = new StringPart(name, String.valueOf(params.get(name)),
		// UTF_8);
		// //System.out.println("post_key==> "+name+"    value==>"+String.valueOf(params.get(name)));
		// }
		// if(files != null)
		// for(String file : files.keySet()){
		// try {
		// parts[i++] = new FilePart(file, files.get(file));
		// } catch (FileNotFoundException e) {
		// e.printStackTrace();
		// }
		// }

		String responseBody = "";
		int time = 0;
		do {
			try {
				httpClient = getHttpClient();
				httpPost = getHttpPost(url, /* cookie, */userAgent);
//				 httpPost.setRequestEntity(new
//				 MultipartRequestEntity(parts,httpPost.getParams()));
				RequestEntity requestEntity = new StringRequestEntity(jsonPost, "text/xml", UTF_8);
				httpPost.setRequestEntity(requestEntity);
				int statusCode = httpClient.executeMethod(httpPost);
				if (statusCode != HttpStatus.SC_OK) {
					throw AppException.http(statusCode);
				} else if (statusCode == HttpStatus.SC_OK) {
					Cookie[] cookies = httpClient.getState().getCookies();
					String tmpcookies = "";
					for (Cookie ck : cookies) {
						tmpcookies += ck.toString() + ";";
					}
					// 保存cookie
					// if(appContext != null && tmpcookies != ""){
					// appContext.setProperty("cookie", tmpcookies);
					// appCookie = tmpcookies;
					// }
				}
				responseBody = httpPost.getResponseBodyAsString();
				break;
			} catch (HttpException e) {
				time++;
				if (time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
					}
					continue;
				}
				// 发生致命的异常，可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				time++;
				if (time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
					}
					continue;
				}
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
				// 释放连接
				httpPost.releaseConnection();
				httpClient = null;
			}
		} while (time < RETRY_TIME);
		responseBody = responseBody.replace('', '?');
		Log.d(TAG,"request url :"+url +"| result :" +responseBody);
		return responseBody;
	}
 
}
